/******************************************************************************
 * Copyright 2022 The Untouch Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#pragma once

#include <fstream>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <vector>

#include "modules/drivers/proto/pointcloud.pb.h"
#include "modules/localization/proto/gps.pb.h"

#include "cyber/cyber.h"
#include "modules/localization/msf/common/util/thread_pool.h"

class RecordData {
 public:
  RecordData();
  ~RecordData();
  bool Start();
  void Stop();
  void SetOdometryTopic(const std::string& topic);
  void SetLidarTopics(const std::vector<std::string>& topics);
  void SetCacheFolderPath(const std::string& path);

 private:
  bool Init();
  void CloseChannel();
  void OdometryCallback(
      const std::shared_ptr<apollo::localization::Gps>& message);
  void LidarCallback(
      const std::shared_ptr<apollo::drivers::PointCloud>& message,
      const std::string& save_path);
  void WritePoseFile(const std::shared_ptr<apollo::localization::Gps>& message);
  void WritePcdFile(const std::shared_ptr<apollo::drivers::PointCloud>& message,
                    const std::string& save_path);
  void AddPcdTimestamps(const std::string& save_path, double timestamp);
  void WritePcdTimestapFile();

 private:
  std::string odometry_topic_;
  std::string cache_folder_path_;
  std::vector<std::string> lidar_topics_;
  std::shared_ptr<apollo::cyber::Node> node_;
  std::shared_ptr<apollo::cyber::Reader<apollo::localization::Gps>>
      odometry_reader_;
  std::vector<
      std::shared_ptr<apollo::cyber::Reader<apollo::drivers::PointCloud>>>
      lidar_readers_;
  std::unique_ptr<apollo::localization::msf::ThreadPool> thread_pool_;
  std::ofstream odometry_loc_stream_;
  std::mutex pcd_timestamps_mutex_;
  std::map<std::string, std::vector<double>> pcd_timestamps_;
};
